//
//  EmoticonView.swift
//  01-表情键盘
//
//  Created by 白利兵 on 15/10/28.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
let emoticonViewCellReuseId = "emotionViewCellReuseId"
let emoticonCellMargin: CGFloat = 8.0
let flowLayoutInset: CGFloat = 6.0
let row: CGFloat = 3
let col: CGFloat = 7
class EmoticonView: UIView {
    // 定义一个表情选中的回调
    private var selectedEmoticonCallBack: (emoticon: Emoticon) -> ()
    // MARK: 构造方法
    init(selectedEmoticon: (emoticon: Emoticon) -> ()) {
        selectedEmoticonCallBack = selectedEmoticon
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 226.0
        
        super.init(frame: rect)
        // 设置UI
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 懒加载表情包数组
    private lazy var packages = EmoticonManager.sharedManager.packages
    // 懒加载toolBar
    private lazy var toolBar = UIToolbar()
    // 懒加载collectionView
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: emoticonLayout())
    
    // 自定义布局类(类中类，只能在本类中调用)
    private class emoticonLayout: UICollectionViewFlowLayout {
        override private func prepareLayout() {
            super.prepareLayout()
            let width = (collectionView?.bounds.width)! / col
            itemSize = CGSizeMake(width, width)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            let margin = ((collectionView?.bounds.height)! - row * width)*0.4999
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            // 4. 设置分页
            collectionView!.pagingEnabled = true
            // 5. 取消弹簧效果
            collectionView!.bounces = false
            collectionView?.backgroundColor = UIColor.lightGrayColor()

        }
    }
    
}
// MARK: 设置UI
extension EmoticonView {
    private func setupUI() {
        toolBar.backgroundColor = UIColor.orangeColor()
        collectionView.backgroundColor = UIColor.whiteColor()
        // 1. 添加控件
        addSubview(toolBar)
        addSubview(collectionView)
        // 2. 设置布局
        // toolBar
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(self.snp_bottom)
            make.height.equalTo(44)
        }
        // collectionView
        collectionView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
            make.top.equalTo(self.snp_top)
        }
        // 3. 准备数据
        prepareCollectionView()
        prepareToolBar()
    }
}

// MARK: 准备collectionView数据
extension EmoticonView {
    private func prepareCollectionView() {
        // 1.注册可重用cell
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: emoticonViewCellReuseId)
        // 2.设置数据源
        collectionView.dataSource = self
        // 3. 设置代理
        collectionView.delegate = self
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 1), atScrollPosition: .Left, animated: false)
        }
        
    }
}

// MARK: 准备toolBar数据
extension EmoticonView {
    private func prepareToolBar() {
        var i = 0
        // 创建按钮数组
        var items = [UIBarButtonItem]()
        for package in packages {
            i = i + 1
           items.append(UIBarButtonItem(title: package.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "itemClick:"))
            items.last?.tag = i
            if i != 4 {
                // 添加弹簧
                items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            }
        }
        toolBar.items = items
    }
    @objc private func itemClick(item: UIBarButtonItem) {
        print("点击了")
        let FromIndexPath = NSIndexPath(forItem: 0, inSection: item.tag-1)
        
        collectionView.scrollToItemAtIndexPath(FromIndexPath, atScrollPosition: .Left, animated: false)
    }
    
}


// MARK: 数据源方法
extension EmoticonView: UICollectionViewDataSource {
    // 返回多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{
        return packages.count
    }
    // 返回多少项
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return packages[section].emoticons.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        // 获取表情包
        let emoticonPackage = packages[indexPath.section]
        // 获取表情
        let emoticon = emoticonPackage.emoticons[indexPath.item]
       let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emoticonViewCellReuseId, forIndexPath: indexPath) as! EmoticonViewCell
    
        //cell.backgroundColor = UIColor.whiteColor()
        cell.emoticon = emoticon
        return cell
    }
}
// MARK: 代理方法
extension EmoticonView: UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //print("点击的是：\(indexPath.item)")
        // 获取表情
        let emoticon = packages[indexPath.section].emoticons[indexPath.item]
        // 闭包回调
        selectedEmoticonCallBack(emoticon: emoticon)
    }
}
// MARK: 自定义cell
class EmoticonViewCell: UICollectionViewCell {

    // 表情模型
    var emoticon: Emoticon? {
        didSet{
            // 设置图片（通过路径名称）
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            // 设置标题（表情的字符串，unicode编码字符串，可以转换为表情图）
            emoticonButton.setTitle(emoticon!.emoji, forState: UIControlState.Normal)
            // 判断是否为删除按钮
            if emoticon?.isRemove == true {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Normal)
            }
            if emoticon?.emoji != nil {}
        }
    }
    // 懒加载控件
    private lazy var emoticonButton: UIButton = {
        let button = UIButton(frame: CGRectInset(self.bounds, 4, 4))
        return button
    }()
    // 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 设置UI
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        emoticonButton.userInteractionEnabled = false
        
        contentView.addSubview(emoticonButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
















